﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;


namespace AMVNewsParser
{
    public partial class FormGrabAMVNews : Form
    {
        WebBrowser wbr = new WebBrowser();
        public FormGrabAMVNews()
        {
            InitializeComponent();
            wbr.MinimumSize = new System.Drawing.Size(20, 20);
            wbr.Name = "wbr";
            wbr.Size = new System.Drawing.Size(764, 389);
            wbr.ScriptErrorsSuppressed = true;
        }

        int maxId;
        int actId;

        private void button1_Click(object sender, EventArgs e)
        {
            maxId = Convert.ToInt32(txbMax.Text);
            actId = Convert.ToInt32(txbMin.Text);
            if (rBtnAmvNews.Checked) wbr.Navigate("http://amvnews.ru/index.php?go=Files&in=view&id=" + actId.ToString());
            if (rBtnAcross.Checked) wbr.Navigate("http://www.akross.ru/index.cgi?act=video;id=" + actId.ToString());
            if (rBtnCreaCon.Checked) wbr.Navigate("http://creaspace.ru/videos/video.php?video_id=" + actId.ToString());
            tmr.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            tmr.Stop();
            try
            {
                if (wbr.ReadyState == WebBrowserReadyState.Complete)
                {
                    label1.Text = "Загружено " + actId.ToString();
                    Application.DoEvents();

                    string html = GetPageHtml(wbr);

                    // запись
                    if (rBtnAmvNews.Checked)
                    {
                        if (!html.Contains("<title>AMV | Клипы</title>"))
                            File.WriteAllText(Gl.dPathHtmlDataAmvNews + "\\" + actId.ToString() + ".html", html, Encoding.UTF8);
                        else
                            if (chbxSaveBadPages.Checked) SaveBadPage(Gl.dPathHtmlDataAmvNews, html);
                    }
                    if (rBtnAcross.Checked)
                    {
                        if (!html.Contains("Этого клипа нет в нашей базе. Возможно, он был удалён."))
                            File.WriteAllText(Gl.dPathHtmlDataAkross + "\\" + actId.ToString() + ".html", html, Encoding.UTF8);
                        else
                            if (chbxSaveBadPages.Checked) SaveBadPage(Gl.dPathHtmlDataAkross, html);
                    }
                    if (rBtnCreaCon.Checked)
                    {
                        if (!html.Contains("<b>Ошибка!</b><ul><li>Нет у нас такого клипа (" + actId.ToString() + ")</ul>"))
                            File.WriteAllText(Gl.dPathHtmlDataCreaCon + "\\" + actId.ToString() + ".html", html, Encoding.UTF8);
                        else
                            if (chbxSaveBadPages.Checked) SaveBadPage(Gl.dPathHtmlDataCreaCon, html);
                    }

                    actId++;
                    if (actId > maxId)
                        return;

                    try
                    {
                        if (rBtnAmvNews.Checked) wbr.Navigate("http://amvnews.ru/index.php?go=Files&in=view&id=" + actId.ToString());
                        if (rBtnAcross.Checked) wbr.Navigate("http://www.akross.ru/index.cgi?act=video;id=" + actId.ToString());
                        if (rBtnCreaCon.Checked) wbr.Navigate("http://creaspace.ru/videos/video.php?video_id=" + actId.ToString());
                    }
                    catch { }

                    tmr.Start();
                }
                else
                {
                    label1.Text = "Загружается " + actId.ToString() + " (" + wbr.ReadyState.ToString() + ")" + (wbr.IsBusy ? "1" : "0");
                    tmr.Start();
                }
            }
            catch (Exception ex) { MessageBox.Show("Ошибка загрузки: " + ex.Message); }
        }

        void SaveBadPage(string DPath, string Html)
        {
            if (!Directory.Exists(DPath + "\\BadPages")) Directory.CreateDirectory(Gl.dPathHtmlDataAmvNews + "\\BadPages");
            File.WriteAllText(DPath + "\\BadPages\\" + actId.ToString() + ".html", Html, Encoding.UTF8);
        }

        string GetPageHtml(WebBrowser Wbr)
        {
            String encodingAS = Wbr.Document.Encoding;
            Encoding hDocEncoding = Encoding.GetEncoding(encodingAS);
            using (System.IO.Stream aStream = Wbr.DocumentStream)
            using (System.IO.StreamReader SR = new System.IO.StreamReader(aStream, hDocEncoding))
            {
                String aText = "";
                while (SR.Peek() >= 0)
                    aText += SR.ReadLine() + "\r\n";
                return aText;
            }
        }
    }
}
